package com.wk.wkplayer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.wk.playersdk.PlayerStateListener;
import com.wk.playersdk.WkPlayer;
import com.wk.playersdk.bean.MuteEnum;
import com.wk.playersdk.bean.TimeInfoBean;
import com.wk.playersdk.bean.WkEventBean;
import com.wk.playersdk.util.WkDeviceInforTool;
import com.wk.playersdk.util.WkException;
import com.wk.playersdk.util.WkFileTool;
import com.wk.playersdk.util.WkLog;
import com.wk.playersdk.util.WkTimeTool;
import com.wk.playersdk.widget.AudioWaveView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.UUID;

public class MainActivity extends Activity {
    private String[] sources= {"http://mpge.5nd.com/2015/2015-11-26/69708/1.mp3",
            "http://ngcdn001.cnr.cn/live/zgzs/index.m3u8" ,
            "/mnt/shared/Other/美丽的神话.mp3",
            "http://oyru0ayig.bkt.clouddn.com/201808150959_osChina_美丽的神话.mp3",
            "http://ngcdn004.cnr.cn/live/dszs/index.m3u8"
    } ;

    private Context context ;
    private WkPlayer wkPlayer;
    private TextView playerState ;
    private TextView tv_time ;
    private TextView tvVolume ;
    private TextView tvDb ;
    private SeekBar seekbarSeek ;
    private SeekBar seekbarVolume ;
    private AudioWaveView dbWaveView;
    /**循环播放*/
    private CheckBox checkboxCircle ;
    /***
     * 当前的播放进度
     */
    private int seekPosition ;
    /**
     * 是否由用户在手动改变进度
     */
    private boolean isSeekingByUser ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this ;
        tv_time= findViewById(R.id.tv_time) ;
        tvVolume = findViewById(R.id.tvVolume) ;
        seekbarVolume = findViewById(R.id.seekbarVolume) ;
        seekbarSeek = findViewById(R.id.seekbarSeek) ;
        tvDb = findViewById(R.id.tvDb) ;
        dbWaveView = findViewById(R.id.dbWaveView) ;
        checkboxCircle = findViewById(R.id.checkboxCircle) ;


        findViewById(R.id.beginplayer ).setOnClickListener(onClickListener);
        findViewById(R.id.stoplayer ).setOnClickListener(onClickListener);
        findViewById(R.id.pauseplayer  ).setOnClickListener(onClickListener);
        findViewById(R.id. resumlayer ).setOnClickListener(onClickListener);
        findViewById(R.id. next ).setOnClickListener(onClickListener);
        findViewById(R.id.leftChannel).setOnClickListener(onClickListener);
        findViewById(R.id.rightChannel).setOnClickListener(onClickListener);
        findViewById(R.id.stereoChannel).setOnClickListener(onClickListener);
        findViewById(R.id.speed).setOnClickListener(onClickListener);
        findViewById(R.id.pitch).setOnClickListener(onClickListener);
        findViewById(R.id.speedpitch).setOnClickListener(onClickListener);
        findViewById(R.id.normalspeedpitch).setOnClickListener(onClickListener);
        findViewById(R.id.startRecord).setOnClickListener(onClickListener);
        findViewById(R.id.pauseRecord).setOnClickListener(onClickListener);
        findViewById(R.id.goonRecord).setOnClickListener(onClickListener);
        findViewById(R.id.stopRecode).setOnClickListener(onClickListener);
        checkboxCircle.setOnCheckedChangeListener(onCheckedChangeListener);



        wkPlayer = new WkPlayer(playerStateListener);
        playerState = findViewById(R.id.playerState) ;
        String strVolum ="音量："+wkPlayer.getVolumePercent()+"%";
        tvVolume.setText(strVolum);
        seekbarVolume.setProgress(wkPlayer.getVolumePercent());
        seekbarVolume.setOnSeekBarChangeListener(seekBarChangeListener);
        seekbarSeek.setOnSeekBarChangeListener(seekBarChangeListenerSeek);
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMsgCome(WkEventBean bean) {
       switch (bean.getCode()){
           case WkEventBean.CODE_1:
               String msg = (String) bean.getData() ;
               msg =playerState.getText().toString()+"-->"+msg ;
               playerState.setText(msg);
               break;
           case WkEventBean.CODE_2:
               int db = (int)bean.getData() ;
               String strdb = "分贝值："+db ;
               tvDb.setText(strdb);
               dbWaveView.updateDataList(db);
               break;
           default:
               break;
       }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMsgCome(TimeInfoBean info) {
        if(info==null){
            return;
        }
        String str = WkTimeTool.secdsToDateFormat(info.getTotalTime() , info.getTotalTime()) ;
        String str2 = WkTimeTool.secdsToDateFormat(info.getCurrentTime() , info.getTotalTime()) ;
        str = str2+" / "+ str ;
        tv_time.setText(str);
        seekbarSeek.setProgress(info.getCurrentTime()*100/info.getTotalTime());
    }




    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.beginplayer:
                    // 准备、初始化
                    //String url = sources[3];
                    //String url = WkFileTool.getAssetsFilePath(context, "audio.mp3") ;
                    String url = WkFileTool.getAssetsFilePath(context, "circlemusic.mp3") ;
                    //String url = WkFileTool.getRawFilePath(context, R.raw.audio ,"audio.mp3");
                    WkLog.d("播放url = "+ url);
                    wkPlayer.setSource( url );
                    wkPlayer.preparePlayer();
                    break;
                case R.id.stoplayer:
                    wkPlayer.stop();
                    break;
                case R.id.pauseplayer:
                    wkPlayer.pause();
                    break;
                case R.id.resumlayer:
                    wkPlayer.resume();
                    break;
                case R.id.next:
                    wkPlayer.playNext(sources[4]);
                    break;
                case R.id.leftChannel:
                    wkPlayer.setMute(MuteEnum.MUTE_LEFT);
                    break;
                case R.id.rightChannel:
                    wkPlayer.setMute(MuteEnum.MUTE_RIGHT);
                    break;
                case R.id.stereoChannel:
                    wkPlayer.setMute(MuteEnum.MUTE_CENTER);
                    break;
                case R.id.speed:
                    wkPlayer.setSpeed(1.5f);
                    wkPlayer.setPitch(1.0f);
                    break;
                case R.id.pitch:
                    wkPlayer.setSpeed(1.0f);
                    wkPlayer.setPitch(1.5f);
                    break;
                case R.id.speedpitch:
                    wkPlayer.setSpeed(1.5f);
                    wkPlayer.setPitch(1.5f);
                    break;
                case R.id.normalspeedpitch:
                    wkPlayer.setSpeed(1.0f);
                    wkPlayer.setPitch(1.0f);
                    break;
                case R.id.startRecord:
                    wkPlayer.startRecord(new File("/mnt/shared/Other/wkRecord.aac"));
                    break;
                case R.id.pauseRecord:
                    wkPlayer.pauseRecord();
                    break;
                case R.id.goonRecord:
                    wkPlayer.reSumeRecord();
                    break;
                case R.id.stopRecode:
                    wkPlayer.stopRecord();
                    break;
                default:
                    break;
            }
        }
    };


    private PlayerStateListener playerStateListener = new PlayerStateListener() {
        @Override
        public void onPrepared() {
            WkLog.d("ffmepg准备完成, 可以 开始播放了");
            wkPlayer.start();
        }

        @Override
        public void onLoad(boolean isLoad) {
            String msg =  isLoad? "正在加载." : "加载完成" ;
            EventBus.getDefault().post(new WkEventBean(WkEventBean.CODE_1 , msg));

        }

        @Override
        public void onPause(boolean isPause) {
            String msg = isPause ? "暂停中" : "播放中" ;
            EventBus.getDefault().post(new WkEventBean(WkEventBean.CODE_1 , msg));
        }

        @Override
        public void onError(int code, String msg) {

        }

        @Override
        public void onComplate() {
            EventBus.getDefault().post(new WkEventBean(WkEventBean.CODE_1 , "播放完成"));
        }

        @Override
        public void onTimeInfo(TimeInfoBean timeInfoBean) {
            EventBus.getDefault().post( timeInfoBean );
        }

        @Override
        public void onDbValue(int db) {
            EventBus.getDefault().post(new WkEventBean(WkEventBean.CODE_2 ,  db));
        }

        @Override
        public void onRecordTime(int recordTime) {

        }
    } ;


    private SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            wkPlayer.setVolume(progress);
            String strVolom = "音量："+progress+"%";
            tvVolume.setText(strVolom);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    } ;

    private SeekBar.OnSeekBarChangeListener seekBarChangeListenerSeek= new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if(isSeekingByUser){
                seekPosition = wkPlayer.getDuration() * progress /100 ;
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekingByUser = true ;

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekingByUser = false ;
            wkPlayer.seek(seekPosition);

        }
    } ;


    private CheckBox.OnCheckedChangeListener  onCheckedChangeListener = new CheckBox.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                wkPlayer.setCirclePlay(isChecked);
//            wkPlayer.seek(0);
        }
    } ;




    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbWaveView.stopView();
    }
}
